<template>
  <wd-collapse
    custom-class="sidebar-collapse" 
    v-model="activeNames" 
    :accordion="level === 0">
    <wd-collapse-item 
      v-for="menu in menus" 
      :key="menu.menuId" 
      :title="menu.menuName" 
      :name="menu.menuId"
      @click="menuClick(menu)"
      :custom-class="menuClass(menu, currentPath)"
      custom-body-style="padding:0 0 0 14px">
      <template v-if="menu.children && menu.children.length">
        <sidebar-menu
          :current-path="currentPath"
          :menus="menu.children" 
          :level="level + 1" />
      </template>
      <!-- <view v-else class="collapse-content">
        <text>{{ menu.menuName }}</text>
      </view> -->
    </wd-collapse-item>
  </wd-collapse>
</template>
<script setup lang="ts">
import { ref, defineEmits, watch } from 'vue';
import Bus from '@/utils/bus';
const emits = defineEmits(['click']);

const props = defineProps({
  menus: {
    type: Array<Menu>,
    required: true
  },
  level: {
    type: Number,
    default: 0
  },
  currentPath: {
    type: String,
    default: ''
  }
})
const isInit = ref<boolean>(true);
const activeNames = ref<string[]>([]);

// 查找当前路径的所有父级菜单ID
const findParentIds = (menus: Menu[], path: string, result: string[] = []): string[] => {
  for (const menu of menus) {
    if (menu.path === path) {
      return result;
    }
    if (menu.children && menu.children.length) {
      const found = findParentIds(menu.children, path, [...result, menu.menuId]);
      if (found) return found;
    }
  }
  return [];
}

// 根据currentPath变化更新展开状态
watch(() => props.currentPath, (newPath) => {
  if (newPath && isInit.value) {
    isInit.value = false;
    activeNames.value = findParentIds(props.menus, newPath);
  }
}, { immediate: true });

const menuClick = (menu: Menu) => {
  if (!(menu.children && menu.children.length)) {
    Bus.emit('menu-children-click', menu);
  }
}

const menuClass = (menu: Menu, curPath: string) => {
  let clazz = '';
  if (menu.path === curPath) {
    clazz += 'active-menu ';
  }
  clazz += menu.children && menu.children.length ? 'badge ' : 'rm-badge ';
  return clazz; 
}
</script>

<style scoped>
:deep(.wd-collapse) {
  background: none !important;
}
:deep(.wd-collapse-item__title) {
  color: var(--font-color) !important;
}
:deep(.wd-collapse-item__content) {
  color: var(--font-color) !important;
  background: var(--theme-color) !important;
}
:deep(.sidebar-collapse .rm-badge .wd-collapse-item__arrow) {
  display: none!important;
}
:deep(.sidebar-collapse .active-menu .wd-collapse-item__title) {
  color: var(--select-menu-font-color) !important;
}
</style>

